package com.inibb.app.util.upload;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.apache.commons.io.IOUtils;

import com.inibb.app.util.io.FileUtil;



public class MimeTypeValidationHandler implements FileHandler{
	private Properties fileConfig;
	
	
	public MimeTypeValidationHandler(Properties fileConfig) {
		super();
		this.fileConfig = fileConfig;
	}

	public ValidationResult handle(File file) {
		
		byte[] b=null;
		ValidationResult vr=new ValidationResult();
		try {
			b=IOUtils.toByteArray(new FileInputStream(file));
			String fileType=FileUtil.getMimeType(b);
			System.out.println(fileType);
			List<String> typelist=getTypes("system.upload.fileContentType");
			System.out.println(typelist.toString());
			int index=typelist.indexOf(fileType);
			
			if(index==-1){
				vr.getErrors().put(file.getName(), "The file content type is not valid. ");
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return vr;
	}
	
	public List<String> getTypes(String limitFileType){
		List<String> list=new ArrayList<String>();
		String limitType=fileConfig.getProperty(limitFileType);
		String[] limitTypes=limitType.split(",");
		for(int i=0;i<limitTypes.length;i++){
			list.add(limitTypes[i]);
		}
		return list;
	}
	
	
	
	public static void main(String[] args) {
		File file=new File("d:/fileupload.properties");
		Properties config=new Properties();
		config.setProperty("system.upload.fileContentType", "image/jpeg,text/plain");
		ValidationResult result=new MimeTypeValidationHandler(config).handle(file);
		System.out.println(result.getErrors().get(file.getName()));
	}

}
